package com.zmn.oms.task.job.perf;

import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.spring.tasktracker.JobRunnerItem;
import com.github.ltsopensource.spring.tasktracker.LTS;
import com.github.ltsopensource.tasktracker.Result;
import com.zmn.common.dto.ResultDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.manager.lts.interfaces.task.TaskManager;
import com.zmn.oms.business.interfaces.perf.PerfCityBService;
import com.zmn.oms.manager.utils.TaskConsts;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

/**
 * 描述: [绩效]城市绩效(菜单名称修改为城市绩效)
 *
 * @author wangjie
 * @date 20:11 2019/3/5
 **/
@LTS
@Slf4j
public class PerfCityJob {

    @Resource
    TaskManager taskManager;

    @Resource
    PerfCityBService perfCityBService;

    /**
     * 城市绩效当前月统计
     * 每天晚上2点统计
     */
    @PostConstruct
    void init() {
        Job job = new Job();
        job.setTaskId(TaskConsts.TASK_ID_PERF_CITY);
        job.setParam(TaskManager.SHARD_FIELD, TaskConsts.TASK_ID_PERF_CITY);
        job.setCronExpression("0 0 02 * * ?");
        job.setReplaceOnExist(true);
        //job.setCronExpression("00 * * * * ?"); // 每60秒执行一次（测试）
        ResultDTO result = taskManager.submitTask(job);
        if (!result.getStatusBool()) {
            log.error("#perf_company_order# job submit fail...");
        }
    }

    /**
     * 描述: 运行城市绩效统计 1、统计当月的 2、如果当前时间是1-5号则需要统计上个月
     *
     * @param job 任务
     * @return com.github.ltsopensource.tasktracker.Result
     * @author wangjie
     * @date 20:15 2019/3/5
     **/
    @JobRunnerItem(shardValue = TaskConsts.TASK_ID_PERF_CITY)
    public Result runPerfCity(Job job) {
        Date now = DateUtil.getNow();
        Date date = DateUtil.addDays(now, -1);
        String dateStr = DateUtil.dateFormatToString(date, DateUtil.FORMAT_DATE);
        String dateStart = DateUtil.getMonthFirstDay(date);
        String dateEnd = dateStr + " 23:59:59";
        perfCityBService.submitCity(dateStart, dateEnd);

        String days = DateUtil.dateFormatToString(now, "dd");
        int intDays = NumberUtil.toInteger(days);
        // 1-5号 统计上个月
        if (intDays >= 1 && intDays <= 5) {
            Date dateMonth = DateUtil.addMonth(now, -1);
            dateStart = DateUtil.getMonthFirstDay(dateMonth);
            dateEnd = DateUtil.getMonthLastDay(dateMonth);
            perfCityBService.submitCity(dateStart, dateEnd);
        }

        log.info("#perf_company_order# 城市绩效统计任务执行成功 ！");
        return new Result(Action.EXECUTE_SUCCESS, "执行成功了!");
    }


}
